package com.augurit.gzcgwsp.ywcmn.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;

import com.augurit.common.base.action.CrudActionSupport;
import com.augurit.common.system.util.WebContextUtils;
import com.augurit.common.system.web.auth.form.LoginUserForm;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.gzcgwsp.webservice.SFTPUtil;
import com.augurit.gzcgwsp.ywcmn.service.IYwComSjclService;
import com.augurit.gzcgwsp.ywcmn.web.form.YwComSjclForm;

@SuppressWarnings("serial")
@Results({
	@Result(name = CrudActionSupport.RELOAD, location = "yw-com-sjcl.action", type = "redirect"),
	@Result(name = CrudActionSupport.SUCCESS, location = "/gzcgwsp/ywcmn/YwComSjcl/YwComSjcl.jsp"),
	@Result(name = CrudActionSupport.INPUT, location = "/gzcgwsp/ywcmn/YwComSjcl/YwComSjcl-input.jsp")
})
public class YwComSjclAction extends CrudActionSupport<YwComSjclForm>{

	@Autowired
	private IYwComSjclService ywComSjclService;
	private static final int FILE_SIZE=16*1024;
	 
	private YwComSjclForm form;
	private Long[] checkedIds;
	private Page<YwComSjclForm> page = new Page<YwComSjclForm>(10);
	private File attach;//附件
	private String attachFileName;//附件名称

	public File getAttach() {
		return attach;
	}

	public void setAttach(File attach) {
		this.attach = attach;
	}

	public String getAttachFileName() {
		return attachFileName;
	}

	public void setAttachFileName(String attachFileName) {
		this.attachFileName = attachFileName;
	}

	/**
	 * ��ҳ��ѯ
	 */
	@Override
	public String list() throws Exception {
		ywComSjclService.search(page, form);
		return SUCCESS;
	}

    public String saveAndLoadSjclBySelectQyxx() throws Exception {
        if (form.getFkid() == null) return null;
        if (form.getAjid() == null) {
            form.setAjid(0L);
        }
        
        ywComSjclService.saveSjclBySelectQyxx(form);
        return null;
    }

	/**
	 * 上传附件
	 * @return
	 * @throws IOException 
	 */
	public String  uploadAttach() throws IOException{
		    Map map=getMapByRequest(getRequest());
		   
			LoginUserForm loginUser = (LoginUserForm) getRequest().getSession()
			.getAttribute(WebContextUtils.SES_LOGIN_USER);
			form.setScr(loginUser.getUser().getUserName());
			form.setSctime(new Date());
				// 随机生成文件名后缀
			String formatDate = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			int random = new Random().nextInt(1000000);
			String context =getRequest().getSession()
						.getServletContext().getRealPath("");
			try {
				if(this.attach!=null){
					String filetype=attachFileName.substring(attachFileName.lastIndexOf(".")+1,attachFileName.length());
					String filename=formatDate+random+"."+filetype;
					String directory=context+File.separator+"resources"+File.separator+"AttacheFile";
					String uploadPath=directory+File.separator+filename;
					String filepath="/resources/AttacheFile/"+filename;
					File targetFile=new File(uploadPath);
					upLoadFile(attach,targetFile);
					//同时上传一份到另外一台服务器
					SFTPUtil.uploadOtherFile(filepath, uploadPath);
					logger.info("附件上传到另外一台机器---------->"+filename);
					form.setFilepath(filepath);
					form.setFiletype(filetype);
					form.setFilename(attachFileName);
					form.setSfdz("0");
					if("Y".equals(form.getOtherFlag())){
						ywComSjclService.saveOtherByUpload(form);
					}else{
						ywComSjclService.saveByUpload(form);
					}					
				}else{
					form.setSfdz("1");
					if("Y".equals(form.getOtherFlag())){
						ywComSjclService.updateOtherAttach(form);
					}else{
						ywComSjclService.updateAttach(form);
					}					
				}
				 JSONObject jsonObject = JSONObject.fromObject(form); 
				 getResponse().setContentType("text/html;charset=UTF-8");
				 getResponse().getWriter().print("<script type='text/javascript'>parent.resultValue('"+jsonObject.toString()+"');</script>");
			} catch (RuntimeException e) {
				e.printStackTrace();
				 getResponse().setContentType("text/html;charset=UTF-8");
				 getResponse().getWriter().print("<script type='text/javascript'>parent.resultValue('{success:true,msg:false}');</script>");
				
			}
			
			
			 
			 return null;
	}
	
	/**
	 * 保存列表增加的其他材料
	 */
	public String  saveOther() throws IOException{
		ywComSjclService.saveOther(form);
		return null;
	}
	
	
	
	 public void upLoadFile(File source,File target){
		  InputStream in=null;
		  OutputStream out=null;
		  try{
		   in=new BufferedInputStream(new FileInputStream(source),FILE_SIZE);
		   out=new BufferedOutputStream(new FileOutputStream(target),FILE_SIZE);
		   byte[] image=new byte[FILE_SIZE];
		   while(in.read(image)>0){
		    out.write(image);
		   }
		  }catch(IOException ex){
		   ex.printStackTrace();
		  }finally{
		   try{
		    in.close();
		    out.close();
		   }catch(IOException ex){
		    
		   }
		  }
		 }
	 
	 
	 public String downloadFile() throws Exception{
		 String url=getRequest().getParameter("url");
		 String filename=getRequest().getParameter("filename");
		 Random random = new Random();  
		 if(StringUtils.isNotBlank(filename)){
			 filename=random.nextInt(1000)+new String(filename.getBytes("iso-8859-1"),"utf-8");
		 }
		 String context=getRequest().getSession().getServletContext().getRealPath("");
		 String path=context+File.separator+url;
		 path=path.replace("/",File.separator);
		 BufferedInputStream bis = null;
         BufferedOutputStream bos = null;
         OutputStream fos = null;
         InputStream fis = null;
         HttpServletResponse resp = null;
         HttpServletRequest request = null;
	       String targetPath = path;
	       try {
	           resp = ServletActionContext.getResponse();
	           request = ServletActionContext.getRequest();
	           //设置字符编码格式
	           resp.setCharacterEncoding("utf-8");
	           try {
	            request.setCharacterEncoding("utf-8");
	           } catch (Exception e1) {
	            e1.printStackTrace();
	           } 
	           File source = new File(targetPath);
	           resp.setContentType("application/force-download");
	           if(StringUtils.isNotBlank(filename)){
	        	   resp.setHeader("Content-Disposition", "attachment; filename=\""
	        			   + source.getName() + "\"");
		                   //+ filename + "\"");
	           }else{
	        	   resp.setHeader("Content-Disposition", "attachment; filename=\""
		                   + source.getName() + "\"");
	           }
	           resp.setHeader("Pragma", "No-cache");
	           resp.setHeader("Cache-Control", "no-cache");
	           fos = resp.getOutputStream();
	           bis = new BufferedInputStream(new FileInputStream(source));
	           byte[] content = new byte[5*1024];
	           int length;
	           while ((length = bis.read(content, 0, content.length)) != -1) {
	               fos.write(content, 0, length);
	           }
	       } catch (Exception e) {
	           e.printStackTrace();
	       } finally {
	               try {
					   fos.close();
//					   fis.close();
					   bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
	           
	       }
	       return null; 
	 }
	
    //获取request对象中所有参数，并设置到map中
    private  Map getMapByRequest(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        Enumeration enu = request.getParameterNames();
        while(enu.hasMoreElements()) {   
            String paraName = (String)enu.nextElement();   
            String paraValue = request.getParameter(paraName).trim(); 
            if(paraValue!=null && !"".equals(paraValue)){
                map.put(paraName, paraValue);
            }
        }  
        return map;
    }	
		
	/**
	 * �������޸�
	 */
	@Override
	public String input() throws Exception {
		return INPUT;
	}

	/**
	 * �������������޸ĵ�Form����
	 */
	@Override
	public String save() throws Exception {
		ywComSjclService.save(form);
		return RELOAD;
	}

	/**
	 * ɾ��һ����¼
	 */
	@Override
	public String delete() throws Exception {
		ywComSjclService.delete(form.getId());
		return RELOAD;
	}
	
	/**
	 * ɾ�������¼
	 */
	@Override
	public String deleteMore() throws Exception{
		ywComSjclService.delete(checkedIds);
		return RELOAD;
	}
	
	/**
	 * ׼��ҳ��ģ��
	 */
	@Override
	protected void prepareModel() throws Exception {
	    String id = super.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			form = ywComSjclService.get(Long.parseLong(id));
		}
		else
			form = new YwComSjclForm();
	}
	

	public YwComSjclForm getModel() {
		return form;
	}
	
	public Long[] getCheckedIds() {
		return checkedIds;
	}

	public void setCheckedIds(Long[] checkedIds) {
		this.checkedIds = checkedIds;
	}
	
	public Page<YwComSjclForm> getPage() {
		return page;
	}


	public void setPage(Page<YwComSjclForm> page) {
		this.page = page;
	}
}
